package cn.kimoon.dau_android;

import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Map;

import cn.kimoon.dau_android.API.ApiDAU;
import cn.kimoon.dau_android.API.AppClient;
import cn.kimoon.dau_android.Model.ModelEngineRoom;
import cn.kimoon.dau_android.Model.ModelEngineRoomItem;
import cn.kimoon.dau_android.pullableview.PullToRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by xiangdong on 2016/11/22.
 */

public class EngineRoomFragment extends Fragment implements AdapterView.OnItemClickListener,
        PullToRefreshLayout.OnRefreshListener, View.OnClickListener{

    public static final int kPageSize = 15;    // 请求数据每一页的数量

    private ModelEngineRoom model;
    private EngineRoomAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
        View view = inflater.inflate(R.layout.fragment_engine_room, container, false);
        initLogicData();
        initSubViews(inflater, view);
        return view;
    }

    // 初始化逻辑数据
    private void initLogicData() {
        model = new ModelEngineRoom();
    }

    // 初始化子View
    private void initSubViews(LayoutInflater inflater, View view) {
        // 刷新控件
        PullToRefreshLayout ptrl = (PullToRefreshLayout) view.findViewById(R.id.refresh_view);
        ptrl.setOnRefreshListener(this);

        // ListView
        View header = (View) inflater.inflate(R.layout.list_engine_header, null, false);
        EditText searchEditText = (EditText) header.findViewById(R.id.engine_search_edit_text);
        searchEditText.setOnClickListener(this);

        ListView listView = (ListView) view.findViewById(R.id.listView);
        listView.addHeaderView(header, null, false);
        listView.setOnItemClickListener(this);
        adapter = new EngineRoomAdapter(null, getActivity());
        listView.setAdapter(adapter);

        // 启动下拉刷新
        ptrl.autoRefresh();
    }

    // ListView点击事件
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        System.out.println("机房列表点击事件" + position);

        ModelEngineRoomItem item = model.result.get(position - 1); // 有了Header，postion会从header开始算

        Intent intent = new Intent(getActivity(), MonitorDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("collectorId", item.id);
        bundle.putString("collectorName", item.name);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    // 刷新控件
    @Override
    public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                // 千万别忘了告诉控件刷新完毕了哦！
//                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
//                Toast.makeText(getActivity(), "刷新完成了", Toast.LENGTH_SHORT).show();
//            }
//        }, 3000);

        requestEngineRoom(pullToRefreshLayout, true);
    }

    @Override
    public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {
        requestEngineRoom(pullToRefreshLayout, false);
    }

    // 按键点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.engine_search_edit_text:
                jumpToSearchActivity();
                break;
        }
    }

    // 跳转到搜索界面
    private void jumpToSearchActivity() {
        startActivity(new Intent(getActivity(), SearchActivity.class));
    }

    // 网络请求
    private void requestEngineRoom(final PullToRefreshLayout pullToRefreshLayout , final boolean isHeader) {
        Map<String, String> parameters = new HashMap<>();
        int page = isHeader ? 0 : model.result.size();
        parameters.put("page", Integer.toString(page));
        parameters.put("size", Integer.toString(kPageSize));
        parameters.put("keyword", "");

        ApiDAU apiDAU = AppClient.retrofit().create(ApiDAU.class);
        Call<ModelEngineRoom> call = apiDAU.apiCollectorList(parameters);
        call.enqueue(new Callback<ModelEngineRoom>() {
            @Override
            public void onResponse(Call<ModelEngineRoom> call, Response<ModelEngineRoom> response) {
                if (response.body() != null && response.body().errCode == 200) {
                    if (isHeader) {
                        model = response.body();
                    } else {
                        model.addMoreData(response.body());
                    }
                    adapter.setData(model.result);
                } else {
                    String msg = (response.body() == null ? response.message() : response.body().msg);
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }
                refreshLayoutEndRefresh(pullToRefreshLayout, isHeader);
            }

            @Override
            public void onFailure(Call<ModelEngineRoom> call, Throwable t) {
                refreshLayoutEndRefresh(pullToRefreshLayout, isHeader);
                Toast.makeText(getActivity(), R.string.internet_request_failed, Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 停止刷新
    private void refreshLayoutEndRefresh(final PullToRefreshLayout pullToRefreshLayout , boolean isHeader) {
        if (isHeader) {
            pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
        } else  {
            pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
        }
    }
}
